//
//  LYSoundManager.swift
//  FlappyBird
//
//  Created by 米明 on 15/6/27.
//  Copyright (c) 2015年 米明. All rights reserved.
//

import UIKit

import AVFoundation

let BGM_NAME = "Stephen Bennett - Maxwell's Silver Hammer.mp3"

class LYSoundManager: NSObject {
    
    static let manager = LYSoundManager()
    var player = AVAudioPlayer()
    var isPlaying = false
    
    func playBeatenMusic(name: String) {

        var soundID = SystemSoundID()
        AudioServicesCreateSystemSoundID(self.getMusicUrl(name: name) as CFURL, &soundID)
        AudioServicesPlaySystemSound(soundID)
    }
    
    func stopMusic() {
        if isPlaying == true {
            player.stop()
            isPlaying = false
        }
    }
    
    func playBackgroundMusic(name: String) {
        
        do {
            player = try AVAudioPlayer(contentsOf: self.getMusicUrl(name: name))
            player.prepareToPlay()
            player.numberOfLoops=1
            player.play()
            isPlaying = true;
        } catch {
            print("AVAudioPlayer init err.")
        }
        
    }
    
    func playDefaultBGM() {
        if DataCenter.getMusicSwitch() {
            self.playBackgroundMusic(name: BGM_NAME)
        }
    }
    
    func getMusicUrl(name: String) -> URL {
        let path = Bundle.main.path(forResource: name, ofType: nil)
        let url = URL(fileURLWithPath: path ?? "")
        return url
    }
    
}
